package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.domain.Jhs99Coupon;
import info.batcloud.fanli.core.domain.TbkRecommendCoupon;
import info.batcloud.fanli.core.entity.TaobaoItemCat;
import info.batcloud.fanli.core.enums.CommissionItemStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.excel.ExcelImporter;
import info.batcloud.fanli.core.helper.CouponHelper;
import info.batcloud.fanli.core.service.CommissionItemImportService;
import info.batcloud.fanli.core.service.CommissionItemService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.service.TaobaoItemCatService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

@Service
public class CommissionItemImportServiceImpl implements CommissionItemImportService {

    private static final Logger logger = LoggerFactory.getLogger(CommissionItemImportServiceImpl.class);

    @Inject
    private TaobaoItemCatService taobaoItemCatService;

    @Inject
    private CommissionItemService commissionItemService;

    @Inject
    private SystemSettingService systemSettingService;

    @Override
    public int importExcel(File file, ImportConfig config) throws FileNotFoundException {

        return importExcel(new FileInputStream(file), config);
    }

    @Override
    public int importExcel(InputStream is, ImportConfig config) {
        logger.info("开始导入商品");
        List<CommissionItemFetchDTO> list = new ArrayList<>();
        switch (config.getSourceFrom()) {
            case JHS_99:
                List<Jhs99Coupon> coupons = ExcelImporter.execute(is, Jhs99Coupon.class, config.isXls());
                list = toJhsCommissionItemFetchBO(coupons);
                break;
            case TBK_RECOMMEND_COUPON:
                List<TbkRecommendCoupon> _coupons = ExcelImporter.execute(is, TbkRecommendCoupon.class, config.isXls());
                list = toCommissionItemFetchBO(_coupons);
                break;
        }
        int total = 0;
        if (list.size() > 0) {
            List<CommissionItemFetchDTO> itemList = new ArrayList<>();
            for (CommissionItemFetchDTO item : list) {
                if (config.isOnlyCoupon() && !item.isCoupon()) {
                    continue;
                }
                if (config.getChannelId() != null) {
                    item.setChannelId(config.getChannelId());
                }
                item.setRecommend(config.isRecommend());
                itemList.add(item);
                if(itemList.size() >= 500) {
                    commissionItemService.saveCommissionItemListSync(itemList);
                    total += itemList.size();
                    itemList.clear();
                }
            }
            if(itemList.size() > 0) {
                commissionItemService.saveCommissionItemListSync(itemList);
            }
            total += itemList.size();
        }
        logger.info("商品导入完成，共导入商品" + total + "个");
        return total;
    }

    private List<CommissionItemFetchDTO> toJhsCommissionItemFetchBO(List<Jhs99Coupon> coupons) {
        List<CommissionItemFetchDTO> dtoList = new ArrayList<>();
        for (Jhs99Coupon co : coupons) {
            CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
            Date now = new Date();
            dto.setListTime(now);
            /**
             * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
             * */
            Date delistTime = DateUtils.addDays(now, 7);
            if(co.getCouponEndTime() == null) {
                co.setCouponEndTime(delistTime);
            }
            dto.setCouponStartTime(co.getCouponStartTime());
            dto.setCouponEndTime(co.getCouponEndTime());
            dto.setDelistTime(Collections.max(Arrays.asList(delistTime, co.getCouponEndTime())));
            TaobaoItemCat taobaoItemCat = taobaoItemCatService.findByName(co.getItemCatName(), 0);
            if (taobaoItemCat != null) {
                dto.setSourceCatId(taobaoItemCat.getCid());
            }
            dto.setShopTitle(co.getShopName());
            dto.setCouponRemainCount(co.getCouponRemainCount());
            dto.setCouponTotalCount(co.getCouponTotalCount());
            dto.setCoupon(true);
            dto.setSummary(co.getCouponInfo());
            if(co.getZkPrice() != null) {
                //说明是优惠券
                dto.setCouponInfo(co.getCouponInfo());
                dto.setCouponValue(co.getPrice() - co.getZkPrice());
                dto.setCouponThresholdAmount(co.getPrice() - 1);
                dto.setCoupon(true);
            } else {
                dto.setCoupon(false);
            }
            dto.setSourceItemUrl(co.getItemUrl());
            dto.setSourceItemId(co.getItemId());
            dto.setTitle(co.getTitle());
            dto.setSourceItemClickUrl(co.getClickUrl());
            dto.setCouponClickUrl(co.getCouponUrl());
            dto.setOriginPrice(co.getPrice());
            dto.setCommissionRate(co.getCommissionRate());
            dto.setEcomPlat(co.getPlatform().trim().equals("淘宝") ? EcomPlat.TAOBAO : EcomPlat.TMALL);
            dto.setImgList(Arrays.asList(co.getPicUrl()));
            dto.setPicUrl(co.getPicUrl());
            dto.setSales(-1); //销量为-1的为预售
            dto.setStatus(CommissionItemStatus.ONSALE);
            dto.setItemPlace(null);
            dto.setRecommend(true);
            dtoList.add(dto);
        }
        return dtoList;
    }

    private List<CommissionItemFetchDTO> toCommissionItemFetchBO(List<TbkRecommendCoupon> coupons) {
        List<CommissionItemFetchDTO> dtoList = new ArrayList<>();
        for (TbkRecommendCoupon co : coupons) {
            CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
            Date now = new Date();
            dto.setListTime(now);
            /**
             * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
             * */
            Date delistTime = DateUtils.addDays(now, 7);
            dto.setCouponStartTime(co.getCouponStartTime());
            dto.setCouponEndTime(co.getCouponEndTime());
            dto.setDelistTime(Collections.max(Arrays.asList(delistTime, co.getCouponEndTime())));
            TaobaoItemCat taobaoItemCat = taobaoItemCatService.findByName(co.getItemCatName(), 0);
            if (taobaoItemCat != null) {
                dto.setSourceCatId(taobaoItemCat.getCid());
            }
            dto.setShopTitle(co.getSellerName());
            dto.setCouponRemainCount(co.getCouponRemainCount());
            dto.setCouponTotalCount(co.getCouponTotalCount());
            dto.setCoupon(true);
            dto.setSummary(co.getCouponInfo());
            dto.setCouponInfo(co.getCouponInfo());
            float[] couponInfos = CouponHelper.parseCouponAmount(co.getCouponInfo());
            dto.setCouponValue(couponInfos[1]);
            dto.setSourceItemUrl(co.getItemUrl());
            dto.setSourceItemId(co.getItemId());
            dto.setTitle(co.getTitle());
            dto.setSourceItemClickUrl(co.getClickUrl());
            dto.setCouponClickUrl(co.getCouponClickUrl());
            dto.setOriginPrice(co.getPrice());
            dto.setCouponThresholdAmount(couponInfos[0]);
            dto.setCommissionRate(co.getCommissionRate());
            dto.setEcomPlat(co.getPlatform().trim().equals("淘宝") ? EcomPlat.TAOBAO : EcomPlat.TMALL);
            dto.setImgList(Arrays.asList(co.getPicUrl()));
            dto.setPicUrl(co.getPicUrl());
            dto.setSales(co.getSales());
            dto.setStatus(CommissionItemStatus.ONSALE);
            dto.setItemPlace(null);
            dto.setRecommend(true);
            dtoList.add(dto);
        }
        return dtoList;
    }
}
